<template>
    <el-card>
        <template #header>
            <div class="flex justify-between items-center">
                <span>图库管理</span>
                <el-button type="primary" @click="showUploadDialog = true">上传图片</el-button>
            </div>
        </template>

        <!-- 搜索框 -->
        <div class="mb-4 flex  items-center gap-2">
            <el-input v-model="searchQuery" placeholder="搜索文件名" prefix-icon="Search" style="width: 200px" @input="handleSearch"/>
            <el-button type="primary" @click="handleReset">重置</el-button>
        </div>

        <!-- 图片列表 -->
        <el-table :data="tableData" v-loading="loading" style="width: 100%">
            <el-table-column prop="fileName" label="文件名" />
            <el-table-column prop="url" label="预览" width="140">
                <template #default="scope">
                    <el-image :src="scope.row.url" :preview-src-list="[scope.row.url]" fit="cover" lazy
                        style="width: 70px; height: 70px; cursor: pointer" preview-teleported :preview-options="{
                            zIndex: 9999,
                            initialIndex: 0,
                            closeOnClickModal: true,
                            closeOnPressEscape: true
                        }" />
                </template>
            </el-table-column>
            <el-table-column prop="size" label="文件大小" width="120">
                <template #default="scope">
                    {{ formatFileSize(scope.row.size) }}
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="上传时间" width="180">
                <template #default="scope">
                    {{ new Date(scope.row.created_at).toLocaleString() }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
                <template #default="scope">
                    <el-button @click="copyImageUrl(scope.row.url)">复制链接</el-button>
                    <el-button type="danger" @click="handleDelete(scope.row.fileName)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background layout="prev, pager, next, total" :total="pagination.totalItems"
            :current-page="pagination.currentPage" :page-size="pagination.itemsPerPage"
            @current-change="handlePageChange" style="margin-top: 20px; justify-content: flex-end;" />

        <!-- 上传对话框 -->
        <el-dialog v-model="showUploadDialog" title="上传图片" width="500px">
            <FileUploader :multiple="false" :accept-types="['image/jpeg', 'image/png', 'image/gif', 'image/webp']"
                :max-size="5" upload-text="点击或拖拽文件到此处上传" @success="handleUploadSuccess" @error="handleUploadError" />
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showUploadDialog = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getFiles, deleteFile } from '@/apis/upload';
import { ElMessage, ElMessageBox } from 'element-plus';
import FileUploader from '@/components/FileUploader.vue';
import {debounce} from 'lodash-es';

// 响应式数据
const tableData = ref([]);
const loading = ref(true);
const searchQuery = ref('');
const showUploadDialog = ref(false);
const pagination = ref({
    currentPage: 1, // 当前页码
    totalPages: 1, // 总页数
    totalItems: 0, // 总文件数
    itemsPerPage: 10 // 每页显示图片数
});

// 获取图片数据
const fetchData = async () => {
    loading.value = true;
    try {
        const res = await getFiles({
            page: pagination.value.currentPage,
            limit: pagination.value.itemsPerPage,
            search: searchQuery.value,
        });

        // 根据API返回的实际数据结构处理
        if (res.success && res.data) {
            // 获取文件列表并清理URL中的反引号
            tableData.value = res.data.files.map(file => ({
                ...file,
                created_at: file.lastModified // 适配表格中使用的created_at字段
            })) || [];

            // 更新分页信息，直接使用后端返回的pagination对象
            if (res.data.pagination) {
                pagination.value = res.data.pagination;
            }
        }
    } catch (error) {
        ElMessage.error('获取图片列表失败');
        console.error('Failed to fetch images:', error);
    } finally {
        loading.value = false;
    }
};

// 处理搜索输入（防抖）
const handleSearch = debounce(() => {
    pagination.value.currentPage = 1; // 重置到第一页
    fetchData();
}, 300); // 300ms 防抖

// 重置搜索
const handleReset = () => {
    searchQuery.value = '';
    handleSearch();
};



// 组件挂载时获取数据
onMounted(fetchData);

// 处理分页变化
const handlePageChange = (page) => {
    pagination.value.currentPage = page;
    fetchData();
};

// 删除图片
const handleDelete = (fileName) => {
    ElMessageBox.confirm('确定要删除这张图片吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            await deleteFile(fileName);
            ElMessage.success('删除成功');
            fetchData();
        } catch (error) {
            ElMessage.error('删除失败');
            console.error('Failed to delete image:', error);
        }
    }).catch(() => { });
};

// 复制图片链接
const copyImageUrl = (url) => {
    navigator.clipboard.writeText(url)
        .then(() => {
            ElMessage.success('链接已复制到剪贴板');
        })
        .catch(() => {
            ElMessage.error('复制失败');
        });
};

// 格式化文件大小
const formatFileSize = (size) => {
    if (!size) return '未知';
    if (size < 1024) return `${size}B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`;
    return `${(size / (1024 * 1024)).toFixed(1)}MB`;
};

// 处理上传成功
const handleUploadSuccess = () => {
    ElMessage.success('上传成功');
    fetchData();
};

// 处理上传错误
const handleUploadError = (errorMsg) => {
    ElMessage.error(errorMsg);
};
</script>

<style scoped>
/* 自定义样式 */
</style>